package com.matrix;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

@Slf4j
public class Dom4jUtil {

    public static Document parse(String path) throws DocumentException {
        SAXReader reader = new SAXReader();
        return reader.read(path);
    }

    public static Element getRootElement(String path) throws DocumentException {
        return parse(path).getRootElement();
    }

    public static Dependency getParentDependency(String path) {
        try {
            Element element = getRootElement(path);
            Element parentNode = element.element("parent");
            if (parentNode == null) {
                return null;
            }
            String groupId = parentNode.element("groupId").getTextTrim();
            String artifactId = parentNode.element("artifactId").getTextTrim();
            String version = parentNode.element("version").getTextTrim();
            Dependency dependency = new Dependency();
            dependency.setGroupId(groupId);
            dependency.setArtifactId(artifactId);
            dependency.setVersion(version);
            return dependency;
        } catch (Exception ignored) {
            return null;
        }
    }

}
